{% extends "../single_page.html" %}

{% block title %}
<title>样本库信息管理 样本库存信息</title>
{% endblock %}

{% block header_title %}
<h1>样本库存信息</h1>
{% endblock %}

{% block header_ol %}
    <li class="breadcrumb-item"><a href="/Home/">Home</a></li>
    <li class="breadcrumb-item">BIS</li>
    <li class="breadcrumb-item active">SampleInventoryInfo</li>
{% endblock %}

{% block card-body %}
<table id="table" class="table table-bordered table-hover dt-responsive">
<thead>
<tr>
    <th>索引</th>
    <th>华大编号</th>
    <th>血浆管数</th>
    <th>癌组织样本数量</th>
    <th>癌旁组织样本数量</th>
    <th>白细胞样本数量</th>
    <th>粪便样本数量</th>
    <th>备注</th>
    <th>上次修改时间</th>
    <th>创建时间</th>
    <th>操作</th>
</tr>
</thead>
</table>
{% endblock %}

{% block ModalForm %}
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
            <label for="sampler_id"> 华大编号</label></span>
        <input type="text" class="form-control" id="sampler_id" name="sampler_id"
               placeholder="请输入华大编号，必填" required="true">
    </div>
    <div class="form-group">
        <label for="plasma_num"> 血浆管数</label>
        <input type="number" step="1" class="form-control" id="plasma_num" name="plasma_num"
               placeholder="请输入血浆管数，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="cancer_tissue_num"> 癌组织数量</label>
        <input type="number" step="1" class="form-control" id="cancer_tissue_num" name="cancer_tissue_num"
               placeholder="请输入癌组织数量，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="adjacent_mucosa_num"> 癌旁组织数量</label>
        <input type="number" step="1" class="form-control" id="adjacent_mucosa_num" name="adjacent_mucosa_num"
               placeholder="请输入癌旁组织数量，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="WBC_num"> 白细胞数量</label>
        <input type="number" step="1" class="form-control" id="WBC_num" name="WBC_num"
               placeholder="请输入白细胞数量，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="stool_num"> 粪便数量</label>
        <input type="number" step="1" class="form-control" id="stool_num" name="stool_num"
               placeholder="请输入粪便数量，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="memo"> 备注</label>
        <input type="text" class="form-control" id="memo" name="memo"
               placeholder="请输入备注，默认：无" value="无">
    </div>
{% endblock %}

{% block page-script %}
<script>
  $(document).ready(function () {
      $("#sidebar_BIS>a").addClass("active");
      $("#sidebar_BIS").addClass("menu-open");
      $("#sidebar_BIS>ul>li:eq(0)>a").addClass("active");
      $(".sidebar").removeAttr("hidden");

      let model0 = "SampleInventoryInfo";
      let url0 = '/api/BIS/' + model0 + '/';
      let id0 = 0;
      let dataModelForm; //更新弹窗默认值，重置按钮需要

      let data0 = $.ajax({
          url: url0, dataType: 'json', contentType: "application/json",
          type: "get", async: false, data: {fields: "id"}
      }).responseJSON;
      $("#card-title1").text("样本库存信息 总条目数： " + data0.length);

      function MyModelInit(title_name, data) {
          dataModelForm = data;
          if (title_name === '更新') {
              $('#sampler_id').val(data['sampler_id']);
              $('#plasma_num').val(data['plasma_num']);
              $('#cancer_tissue_num').val(data['cancer_tissue_num']);
              $('#adjacent_mucosa_num').val(data['adjacent_mucosa_num']);
              $('#WBC_num').val(data['WBC_num']);
              $('#stool_num').val(data['stool_num']);
              $('#memo').val(data['memo']);
              $('#type').val('edit');
              $('#modal_title').text('更新');
          } else {
              $('#sampler_id').val("");
              $('#plasma_num').val("");
              $('#cancer_tissue_num').val("");
              $('#adjacent_mucosa_num').val("");
              $('#WBC_num').val("");
              $('#stool_num').val("");
              $('#memo').val("");
              $('#type').val('new');
              $('#modal_title').text('新增');
          }
      }

      let table = $('#table').DataTable({
          "paging": true,
          "ordering": true,
          "info": true,
          "autoWidth": false,
          "responsive": true,
          "language": {
              "lengthMenu": "选择每页 _MENU_ 展示 ",
              "zeroRecords": "未找到匹配结果--抱歉",
              "info": "当前显示第 _PAGE_ 页结果，共 _PAGES_ 页",
              "infoEmpty": "没有数据",
              "search": "搜索",
              "infoFiltered": "(获取 _MAX_ 项结果)",
              "paginate": {
                  "first": "首页",
                  "previous": "上一页",
                  "next": "下一页",
                  "last": "末页"
              },
              "buttons": {
                  "colvisRestore": "重置"
              }
          },
          "scrollY": "500px",
          "scrollCollapse": true,
          "scrollX": true,
          "pagingType": "full_numbers",
          //"fixedColumns": true,
          "rowReorder": true,
          "colReorder": true,
          "searching": true,
          "select": true,
          "fixedHeader": true,
          "lengthChange": true,
          "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
          "serverSide": true,
          "processing": true,
          "deferRender": true,
          "dom": 'rilB<"clear">ftp',
          "buttons": [
              /*
              {
                extend: 'pageLength',
                text: '显示行数'
              },
              */

              {
                  text: '指定显示列', extend: 'colvis',
                  className: 'btn btn-info btn btn-info far fa-eye my-1 dropdown-toggle',
                  postfixButtons: [
                      {
                          extend: 'colvisGroup',
                          text: '显示前5列',
                          className: 'dt-button buttons-columnVisibility',
                          show: [0, 1, 2, 3, 4, 5, 10],
                          hide: [6, 7, 8, 9]
                      },
                      { extend: 'colvisGroup',
                          text: '显示全部列',
                          className: 'dt-button buttons-columnVisibility',
                          show: ':hidden'
                      }],
                  columnText: function (dt, idx, title) {
                      return (idx + 1) + ': ' + title;
                  }
              },
              {
                  extend: 'selectNone',
                  className: 'btn btn-primary fas fa-ban my-1',
                  text: '取消当前选择'
              },
              {
                  extend: 'csv',
                  text: '所选输出到csv',
                  className: 'btn btn-success fas fa-file-csv my-1',
                  exportOptions: {
                      columns: range(10)
                  }
              },
              {
                  extend: 'csv',
                  text: '全部输出到csv',
                  className: 'btn btn-success fas fa-file-excel my-1',
                  exportOptions: {
                      columns: range(10),
                      selected: null
                  }
              },
              {
                  text: '添加单行',
                  className: 'btn btn-warning fas fa-edit my-1',
                  action: function (e, dt, node, config) {

                  },
                  attr: {
                      id: 'new'
                  }
              },
            {% if perms.BIS.bulk_update_SampleInventoryInfo %}
              {
                  text: '批量添加模板下载',
                  className: 'btn btn-success fas fa-download my-1',
                  action: function ( e, dt, node, config ) {

                  },
                  attr: {
                      id: 'downloadExcel'
                  }
              },
              {
                  text: '批量添加',
                  className: 'btn btn-warning fas fa-upload my-1',
                  action: function ( e, dt, node, config ) {

                  },
                  attr: {
                      id: 'upload'
                  }
              },
            {% endif %}
            {% if perms.BIS.bulk_delete_SampleInventoryInfo %}
              {
                  text: '批量删除',
                  className: 'btn btn-danger fas fa-trash-alt my-1',
                  action: function ( e, dt, node, config ) {

                  },
                  attr: {
                      id: 'bulkDel'
                  }
              },
            {% endif %}
          ],
          "ajax": url0 + "?format=datatables",
          "columns": [
              {
                  data: 'id',
                  width: "1%",
                  // 若想前端显示的不一样，则需要"render"函数
                  'render': function (data, type, full, meta) {
                      return meta.row + 1 + meta.settings._iDisplayStart;
                  }
              },
              {"data": "sampler_id"},
              {"data": "plasma_num"},
              {"data": "cancer_tissue_num"},
              {"data": "adjacent_mucosa_num"},
              {"data": "WBC_num"},
              {"data": "stool_num"},
              {"data": "memo"},
              {"data": "last_modify_time"},
              {"data": "create_time"},
              {
                  "data": null,
                  "defaultContent": '<button type="button" class="btn btn-info">更新</button>' + '&nbsp;&nbsp' +
                    '<button type="button" class="btn btn-danger">删除</button>'
              }
          ],
          "columnDefs": [
              {"targets": [6, 7, 8, 9],
                "visible": false}]
      });
      // $('#table tbody').on( 'click', 'tr', function () {
      //     $(this).toggleClass('selected');
      // });


      $('#table tbody').on('click', 'button', function () {
          let data = table.row($(this).parents('tr')).data();
          let class_name = $(this).attr('class');
          id0 = data['id'];
          console.info("click button, id:", id0)
          //alert(id);
          if (class_name === 'btn btn-info') {
              // EDIT button
              MyModelInit('更新', data);
              $("#myModal").modal();
          } else {
              // DELETE button
              // alert('delete '+id);
              // $('#modal_title').text('DELETE');
              $("#confirm").modal();
          }
      });

      $('#modelForm').on('submit', function (e) {
          e.preventDefault();
          // 递交前检查，一般是检测model的外键是否存在

          let type = $('#type').val();
          let method = '';
          let url_ajax0 = url0;
          if (type === 'new') {
              // new
              method = 'POST';
              // POST前检查，一般是检测model的关键字段值是否存在
              data0 = $.ajax({
                  url: url0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: {sampler_id: $('#sampler_id').val()}
              }).responseJSON[0];
              if (data0 !== undefined) {
                  $('#myModalError').text('错误！！！华大编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                  return
              }
          } else {
              // edit
              url_ajax0 = url0 + id0 + '/';
              method = 'PUT';
          }
          
          $.ajax({
              url: url_ajax0,
              method: method,
              data: $(this).serialize(),
              headers: {'X-HTTP-Method-Override': 'PATCH'},
              success: function () {
                  let v_tmp = $('#sampler_id').val();
                  if (type === 'new') {
                      databaseRecordAjaxPut(model0, "单项添加", "华大编号：" + v_tmp);
                      $('#myModalError').text('添加成功！！！华大编号：' + v_tmp);
                  } else {
                      databaseRecordAjaxPut(model0, "单项更新", "华大编号：" + v_tmp);
                      $('#myModalError').text('更新成功！！！华大编号：' + v_tmp);
                  }

                  setTimeout(
                      function () {
                          window.location.reload(true);
                      }, 3000
                  );
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  $('#myModalError').text('出现错误！！！请联系管理员');
                  console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
              }
          });
      });

      $('#confirm').on('click', '#delete', function (e) {
          let res = delete_by_id_simple(url0, id0);
          if (res[0] === "success") {
              databaseRecordAjaxPut(model0, "单项删除", "id：" + res[1]);
              window.location.reload(true);
          } else {
              console.log(res[1]);
          }
      });

      $('#new').on('click', function (e) {
          MyModelInit('新增', {});
          $("#myModal").modal();
      });

      $('#upload').on('click', function (e) {
          $('#uploadOperator').val("");
          $('#uploadFile').val("");
          $('#uploadError').val("");
          $('#uploadUrl').val(model0);
          $("#uploadModal").modal();
      });

      $('#bulkDel').on('click', function (e) {
          $('#bulkDelUrl').val(model0);
          $("#bulkDelModal").modal();
      });

      $('#bulkDelModal').on('click', '#bulkDelete', function (e) {
          let arrayLen = table.rows(".selected").data().length;
          if (arrayLen > 0) {
              let delete_id_list = [];
              for (let i = 0; i < arrayLen; i++) {
                  let delete_id = table.rows(".selected").data()[i]['id'];
                  let res = delete_by_id_simple(url0, delete_id);
                  if (res[0] === "success") {
                      delete_id_list.push(res[1]);
                  }
              }
              databaseRecordAjaxPut(model0, "批量删除", "id_list：[" + delete_id_list + "]");
              window.location.reload(true);
          } else {
              $('#bulkDelError').text('没有行被选中，请先选中目标行。');
          }
      });

      $('.downloadExcel').on('click', function (e) {
          e.preventDefault();
          window.location.href = '/ADVANCE/download_excel/BIS_' + model0 + '/'
      });

      $('#myModalReset').on('click', function (e) {
          e.preventDefault();
          if ($('#modal_title').text() === '更新') {
              MyModelInit('更新', dataModelForm);
          } else {
              MyModelInit('新增', {});
          }
      });

      $("#modelForm input[type='text']").focus(function () {
          let key2 = $(this).attr('id');
          let values = $.ajax({
              url: "{% url 'ADVANCE:unique' %}", data: {model: model0, filed: key2},
              dataType: 'json', contentType: "application/json",
              method: "GET", async: false
          }).responseJSON.values;
          console.info("values:", values, "; key2:", key2);
          input_autocomplete(values, '#' + key2);
      });

  });
</script>
{% endblock %}
